# import json
#
# import requests
#
# url = "https://m.douban.com/rexxar/api/v2/subject/recent_hot/tv?limit=50"
#
# headers = {
#     'User-Agent':"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36",
#     "Referer": "https://m.douban.com/tv/",
# }
#
# response = requests.get(url,headers=headers)
# print(response.status_code)
# data = response.json()
# #
# for item in data["items"]:
#     print(item)
#     pic_dict = item.get("pic", {})
#     pic_url = pic_dict.get("normal")
#     pic_response = requests.get(pic_url)
#
#
#     with open('豆瓣电影.json', "a", encoding="utf-8") as f:
#         json.dump(item, f, ensure_ascii=False, indent=2)


# items = data.get("items", [])  # 安全获取 items 列表，避免 KeyError
#
# with open('豆瓣电影.json', "w", encoding="utf-8") as f:
#         # 写入整个 items 列表，indent=2 格式化显示
#     json.dump(items, f, ensure_ascii=False, indent=2)

#多个板块，相似爬法
import json
import os
import requests

# 目标URL和请求头
url = "https://m.douban.com/rexxar/api/v2/subject/recent_hot/tv?limit=50"
headers = {
    'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36",
    "Referer": "https://m.douban.com/tv/",
}

# 1. 获取所有电视剧数据
response = requests.get(url, headers=headers)
print("请求状态码：", response.status_code)  # 确保状态码为200
data = response.json()
items = data.get("items", [])  # 提取所有条目，避免KeyError

# 2. 创建图片保存目录（如不存在）
pic_dir = "豆瓣电视剧图片"
if not os.path.exists(pic_dir):
    os.makedirs(pic_dir)

# 3. 保存所有数据到JSON文件（一次性写入，避免覆盖）
with open('豆瓣电影.json', "w", encoding="utf-8") as f:
    json.dump(items, f, ensure_ascii=False, indent=2)  # 写入整个列表
print(f"已保存 {len(items)} 条数据到 JSON 文件")

# 4. 遍历数据并下载图片
for i, item in enumerate(items, 1):
    title = item.get("title", f"未知标题_{i}")
    print(f"\n处理第 {i} 条：{title}")

    # 获取图片URL
    pic_dict = item.get("pic", {})
    pic_url = pic_dict.get("normal")
    if not pic_url:
        print(f"⚠️ {title} 无图片URL，跳过下载")
        continue

    # 下载并保存图片
    try:
        # 发送图片请求（添加超时和 headers 避免被拦截）
        pic_response = requests.get(pic_url, headers=headers, timeout=10)
        pic_response.raise_for_status()  # 检查请求是否成功

        # 处理文件名特殊字符（避免保存失败）
        safe_title = title.replace("/", "-").replace("\\", "-").replace(":", "-")
        pic_path = os.path.join(pic_dir, f"{safe_title}.jpg")

        # 写入图片文件
        with open(pic_path, "wb") as pic_f:
            pic_f.write(pic_response.content)
        print(f"✅ 图片已保存：{pic_path}")

    except Exception as e:
        print(f"❌ 下载 {title} 图片失败：{str(e)}")